package chap04.Queue;

/**
 * Created by root on 2017/7/14.
 */
public class QueueX{
    private int maxSize;
    private long[] queueArray;
    private int front;
    private int rear;
    private int nItems;

    public QueueX(int maxSize) {
        this.maxSize = maxSize;
        queueArray = new long[maxSize];
        front = 0;
        rear = -1;
        nItems = 0;
    }

    public void insert(long j) {
        if (isFull()) {
            System.out.println("can't insert,");
            return;
        }
        rear++;
        if (rear==maxSize) {
            rear = 0;
        }
        queueArray[rear] = j;
        nItems++;
    }


    public long remove() {
        if (isEmpty()) {
            System.out.println("can't remove");
            return 0;
        }
        nItems--;
        long value = queueArray[front];
        front++;
        if (front==maxSize) {
            front=0;
        }
        return value;
    }

    public long peek() {
        return queueArray[front];
    }

    public boolean isEmpty() {
        return (nItems==0);
    }

    public boolean isFull() {
        return (nItems==maxSize);
    }

    public void displayQueue(){
        if (rear>front) {
            for (int i=front; i<=rear; i++) {
                System.out.print(queueArray[i] + " ");
            }
        } else {
            for (int i=front; ; i++) {
                if (i == maxSize) {
                    i = -1;
                    continue;
                }
                System.out.print(queueArray[i] + " ");
                if(i == rear){
                    break;
                }
            }
        }
        System.out.println();
    }
}
